package megrez.keycloak.providers.password;

import org.keycloak.credential.hash.PasswordHashProvider;
import org.keycloak.models.PasswordPolicy;
import org.keycloak.models.credential.PasswordCredentialModel;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * 自定义加密方法
 * 
 * @author Lucky Yang
 * @since 2.6.9
 */
public class CustomPasswordHashProvider implements PasswordHashProvider {
    private final PasswordEncoder encoder;


    public CustomPasswordHashProvider(PasswordEncoder passwordEncoder) {
        this.encoder = passwordEncoder;
    }

    @Override
    public void close() {
        // 不需要实现
    }

    @Override
    public boolean policyCheck(PasswordPolicy policy, PasswordCredentialModel credential) {
        return credential.getPasswordCredentialData().getHashIterations() == policy.getHashIterations()
                && CustomPasswordHashProviderFactory.PROVIDER_ID
                        .equals(credential.getPasswordCredentialData().getAlgorithm());
    }

    @Override
    public PasswordCredentialModel encodedCredential(String rawPassword, int iterations) {
        String encodedPassword = encoder.encode(rawPassword);

        return PasswordCredentialModel.createFromValues(CustomPasswordHashProviderFactory.PROVIDER_ID, null, iterations,
                encodedPassword);
    }

    @Override
    public boolean verify(String rawPassword, PasswordCredentialModel credential) {
        return encoder.matches(rawPassword, credential.getPasswordSecretData().getValue());
    }

}
